//
//  ViewController.m
//  MVVMTest
//
//  Created by WestWood on 2019/2/20.
//  Copyright © 2019 WestWood. All rights reserved.
//

#import "ViewController.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import "PersonViewModel.h"
#import "ReactiveViewController.h"

@interface ViewController () <PersonViewModelDelegate>

@property(nonatomic, strong) PersonViewModel *personViewModel;

@property(nonatomic, strong) UILabel *label;

@property(nonatomic, strong) UILabel *lastNameLable;

@property(nonatomic, strong) UILabel *salutionLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib
    [self initialView];
    // context用于区分不同的监听器，那如果添加了多个监听而且没有加以却别，如何进行区分呢？？？
    [self.personViewModel addObserver:self forKeyPath:@"person.firstName" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)viewWillDisappear {
    [self removeObserver:self forKeyPath:@"person.firstName"];
}

- (void)initialView {
    UIButton *buttonn = [[UIButton alloc] init];
    [buttonn setFrame:CGRectMake(100, 400, 150, 70)];
    [buttonn setBackgroundColor:[UIColor orangeColor]];
    [buttonn setTitle:@"KVO测试" forState:UIControlStateNormal];
    [self.view addSubview:buttonn];
    [buttonn addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *combineButton = [[UIButton alloc] init];
    [combineButton setFrame:CGRectMake(100, 500, 150, 70)];
    [combineButton setBackgroundColor:[UIColor orangeColor]];
    [combineButton setTitle:@"合并流" forState:UIControlStateNormal];
    [self.view addSubview:combineButton];
    [combineButton addTarget:self action:@selector(combineButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *mapButtonn = [[UIButton alloc] init];
    [mapButtonn setFrame:CGRectMake(100, 600, 150, 70)];
    [mapButtonn setBackgroundColor:[UIColor orangeColor]];
    [mapButtonn setTitle:@"遍历流" forState:UIControlStateNormal];
    [self.view addSubview:mapButtonn];
    [mapButtonn addTarget:self action:@selector(addMapping) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *racButton = [[UIButton alloc] init];
    [racButton setFrame:CGRectMake(100, 700, 150, 70)];
    [racButton setBackgroundColor:[UIColor orangeColor]];
    [racButton setTitle:@"addRacObeserve" forState:UIControlStateNormal];
    [self.view addSubview:racButton];
    [racButton addTarget:self action:@selector(addRacObeserve) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *pushButton = [[UIButton alloc] init];
    [pushButton setFrame:CGRectMake(100, 800, 150, 70)];
    [pushButton setBackgroundColor:[UIColor orangeColor]];
    [pushButton setTitle:@"Rac冷信号测试" forState:UIControlStateNormal];
    [self.view addSubview:pushButton];
    [pushButton addTarget:self action:@selector(pushToReactive) forControlEvents:UIControlEventTouchUpInside];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 300, 100)];
    
    [self.label setText:self.personViewModel.person.firstName];
    [self.view addSubview:self.label];
    
    self.lastNameLable = [[UILabel alloc] initWithFrame:CGRectMake(100, 150, 300, 100)];
    [self.lastNameLable setText:[[self.personViewModel person] lastName]];
    [self.view addSubview:self.lastNameLable];
    [self.personViewModel setDelegate:self];
    
    self.salutionLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 300, 100)];
    [self.salutionLabel setText:[[self.personViewModel person] salutation]];
    [self.view addSubview:self.salutionLabel];
}

- (void)addRacObeserve {
//    RACSignal *letters = [@"A B C D E F G H I" componentsSeparatedByString:@" "].rac_sequence.signal;
//    [letters subscribeNext:^(NSString *x) {
//        NSLog(@"changed value %@", x);
//    }];
//
//
//    // 这是不进行 reject的冷信号观察
//    __block unsigned subscripters = 0;
//    RACSignal *loggingSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
//        subscripters++;
//        [subscriber sendCompleted];
//        return nil;
//    }];
//
//    NSLog(@"subscripters %d", subscripters);
//    [loggingSignal subscribeCompleted: ^{
//        NSLog(@"subscripters %d", subscripters);
//    }];
//
//    [loggingSignal subscribeCompleted: ^{
//        NSLog(@"subscripters %d", subscripters);
//    }];
//
//    // 有reject 的冷信号的观察
//    __block unsigned rejectSubscripters = 0;
//    RACSignal *rejectLogginSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
//        rejectSubscripters++;
//        [subscriber sendCompleted];
//        return nil;
//    }];
//
//    // do nothing yet
//    rejectLogginSignal = [rejectLogginSignal doCompleted:^{
//        NSLog(@"about to complete subscripter %u", rejectSubscripters);
//    }];
//
//    // abount to complete subscription 1
//    [rejectLogginSignal subscribeCompleted:^{
//        NSLog(@"rejectSubscripters %u", rejectSubscripters);
//    }];
    
    
    RACSignal *letters = [@"a b c d e f g h i" componentsSeparatedByString:@" "].rac_sequence.signal;
    [letters subscribeNext:^(NSString *x) {
        NSLog(@"%@", x);
    }];
}

#pragma mark -----------遍历流---------------
- (void)addMapping {
    RACSequence *letters = [@"a b c d e f g h i" componentsSeparatedByString:@" "].rac_sequence;
    RACSequence *mapped = [letters map:^id _Nullable(NSString *value) {
        return [value stringByAppendingString:value];
    }];
    
    RACSignal *mapSignal = mapped.signal;
    [mapSignal subscribeCompleted:^{
        NSLog(@"next mapSignal and next we will be a goog job");
    }];
    [mapSignal subscribeNext:^(NSString *value) {
        NSLog(@"subscribeNext == %@", value);
    }];
    
    RACSequence *numbers = [@"1 2 3 4 5 6 7 8 9" componentsSeparatedByString:@" "].rac_sequence;
    // Constainers: 2 4 6 8
    RACSequence *filtered = [numbers filter:^BOOL(NSString *value) {
        return (value.intValue % 2) == 0;
    }];
    
    [filtered.signal subscribeCompleted:^{
        NSLog(@"good job");
    }];
}

- (void)buttonClicked {
    //    PersonViewModel
    [self.personViewModel changePersonLastName:@"test"];
    [self.personViewModel changePersonFirstName];
}

#pragma mark -----------合并流------------
- (void)combineButtonClicked {
    [self sequenceFlatten];
    [self signalFlatten];
}

- (void)sequenceFlatten {
    RACSequence *letters = [@"A B C D E F G H I" componentsSeparatedByString:@" "].rac_sequence;
    RACSequence *numbers = [@"1 2 3 4 5 6 7 8 9" componentsSeparatedByString:@" "].rac_sequence;
    RACSequence *sequenceOfSequence = @[letters, numbers].rac_sequence;
    RACSequence *flattened = [sequenceOfSequence flatten];
    [flattened.signal subscribeNext:^(NSString *x) {
        NSLog(@"flatten----------------- Sequence合并: %@", x);
    }];
}

- (void)signalFlatten {
    RACSubject *letters = [RACSubject subject];
    RACSubject *numbers = [RACSubject subject];
    RACSignal *signalOfSignals = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:letters];
        [subscriber sendNext:numbers];
        [subscriber sendCompleted];
        return nil;
    }];
    
    RACSignal *flatten = [signalOfSignals flatten];
    
    [flatten subscribeNext:^(NSString *x) {
        NSLog(@"subscribeNext---------------Signal信号合并: %@",x);
    }];
    
    [letters sendNext:@"a"];
    [numbers sendNext:@"1"];
    [letters sendNext:@"b"];
    [numbers sendNext:@"2"];
    [letters sendNext:@"c"];
    [numbers sendNext:@"3"];
}


- (PersonViewModel *)personViewModel {
    if (!_personViewModel) {
        _personViewModel = [[PersonViewModel alloc] initWithPerson:[[Person alloc]
                                                                    initwithSalutation:@"Fuck off"
                                                                    firstName:@"爆发力"
                                                                    lastName:@"开始接电话"
                                                                    birthdate:[NSDate date]]];
    }
    return _personViewModel;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    NSLog(@"侦测到变化%@", self.personViewModel.person.firstName);
    // 侦测到变化进行修改
    [self.label setText:self.personViewModel.person.firstName];
}


- (void)personHadChange:(Person *)person {
    NSLog(@"%@", person.description);
    [self.lastNameLable setText:person.lastName];
}


- (void)pushToReactive {
    ReactiveViewController *reactiveCocoaTest = [[ReactiveViewController alloc] init];
    [self presentViewController:reactiveCocoaTest animated:TRUE completion:nil];
}

@end
